<template>
  <el-dialog
    :visible="visible"
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    @close="dialogClose"
    @open="dialogOpen"
  >
    <!-- 权限点树形数据 -->
    <el-tree
      ref="treeRef"
      :data="treeList"
      :props="{ label: 'name' }"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
    />
    <!-- 按钮区域 -->
    <template #footer>
      <div style="text-align: right">
        <el-button @click="$emit('dialog-close')">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleDetail } from '@/api/setting'
import { getPermissionList, assignPermission } from '@/api/permission'
import transTree from '@/utils/transTree'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      treeList: []

    }
  },
  methods: {
    // 弹窗关闭，执行的回调
    dialogClose() {
      this.$emit('dialog-close')
    },
    async fetchPermissionList() {
      // 发送请求, 获取所有权限点列表
      const res = await getPermissionList()
      this.treeList = transTree(res.data, '0')
      const roleDetail = await getRoleDetail(this.roleId)
      this.$refs.treeRef.setCheckedKeys(roleDetail.data.permIds)
    },
    dialogOpen() {
      this.fetchPermissionList()
    },
    async submit() {
      // 调用接口
      await assignPermission({
        id: this.roleId,
        // getCheckedKeys 方法：返回目前被选中的节点的 key 所组成的数组
        // key 我们设置的是数据中的 id 值
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      // 提示用户
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.dialogClose()
    }
  }
}
</script>
